<template>
  <van-nav-bar title="地址列表" left-text="返回" left-arrow @click-left="goBack" />
  <!-- 显示订单的收货地址列表 -->
  <van-address-list
    v-if="action == 'order'"
    v-model="chosenAddressId"
    :list="list"
    default-tag-text="默认"
    @select="ChangeOrderSelect"
    @add="onAdd"
    @edit="onEdit"
  />
  <!-- 收货地址列表 -->
  <van-address-list
    v-else
    v-model="chosenAddressId"
    :list="list"
    default-tag-text="默认"
    @select="ChangeSelect"
    @add="onAdd"
    @edit="onEdit"
  />
</template>
<script setup>
const { cookies } = useCookies();
const router = useRouter();
const route = useRoute();
const LoginUser = reactive(cookies.get("LoginUser"));
const list = ref([]);
const action = ref("");
const chosenAddressId = ref("1");

onMounted(() => {
  action.value = route.query.action ? route.query.action : "";
  getAddressData();
});

const goBack = () => {
  if (action.value == "order") {
    router.go(-1);
  } else {
    router.push("/business/base/index");
  }
};

const getAddressData = async () => {
  let result = await Api.addressIndex({ id: LoginUser.id });
  if (result.code == 1) {
    list.value = [];
    result.data.forEach((item) => {
      list.value.push({
        id: item.id,
        name: item.consignee,
        tel: item.mobile,
        address: item.address_text,
        isDefault: item.status == 1 ? true : false,
      });
      if (item.status == 1) {
        chosenAddressId.value = item.id;
      }
    });
  }
};

const onAdd = () => {
  router.push("/business/address/add");
};

const ChangeSelect = async (val) => {
  let result = await Api.addressCheck({ busid: LoginUser.id, id: val.id });
  if (result.code == 1) {
    getAddressData();
    showNotify({ type: "success", message: result.msg });
  } else {
    showNotify({ type: "danger", message: result.msg });
  }
};

const onEdit = (val) => {
  router.push({
    path: "/business/address/edit",
    query: {
      id: val.id,
    },
  });
};

// 订单选择地址
const ChangeOrderSelect = (val) => {
  let data = {
    id: val.id,
    mobile: val.tel,
    consignee: val.name,
  };
  cookies.set("addressinfo", data);
  goBack();
};
</script>
